<!-- 导入组件 -->
<template>
  <Dialog v-model="dialogVisible" title="导入" width="600" :close-on-click-modal="false">
    <el-upload
      ref="uploadRef"
      v-model:file-list="fileList"
      :action="
        importUrl +
        '?mode=' +
        mode +
        '&file=' +
        file +
        '&updatePart=' +
        updatePart +
        '&outFile=' +
        outFile +
        '&fromInventoryStatus=' + fromInventoryStatus +
        '&toInventoryStatus=' + toInventoryStatus
      "
      :auto-upload="false"
      :disabled="formLoading"
      :headers="uploadHeaders"
      :limit="1"
      :on-error="submitFormError"
      :on-exceed="handleExceed"
      :on-success="submitFormSuccess"
      :accept="accept"
      drag
      style="width: 300px; margin: 0 auto"
      v-loading="formLoading"
    >
      <Icon icon="ep:upload-filled" color="#c0c4cc" size="60" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip ml--126px mr--80px">
          <div class="flex">
            <div
              class="label h-32px mr-26px color-#acaeb3 font-size-14px w-100px text-right"
              style="line-height: 32px"
              >导入模式</div
            >
            <div class="">
              <div class="radio">
                <el-radio-group v-model="mode">
                  <el-radio :label="1" :disabled="updateIsDisable">更新</el-radio>
                  <el-radio :label="2" :disabled="appendIsDisable">追加</el-radio>
                  <el-radio :label="3" :disabled="coverIsDisable">覆盖</el-radio>
                </el-radio-group>
              </div>

              <div class="tips color-#acaeb3 font-size-14px">
                <div class="mt-2">更新：新增并修改</div>
                <div class="mt-2">追加：只新增，不修改</div>
                <div class="mt-2">覆盖：只修改不新增</div>
              </div>
            </div>
          </div>
          <div class="flex mt-16px">
            <div
              class="label h-32px mr-26px color-#acaeb3 font-size-14px w-100px text-right"
              style="line-height: 32px"
              >部分保存</div
            >
            <div class="">
              <div class="switch">
                <el-switch v-model="updatePart" />
              </div>
              <div class="tips color-#acaeb3 font-size-14px">
                <div class="mt-2">部分保存：如存在错误数据，正确数据正常导入</div>
                <div class="mt-2">全部保存：全部数据正确，才能导入</div>
              </div>
            </div>
          </div>
          <div class="flex mt-16px" v-if="isShowOut">
            <div
              class="label h-32px mr-26px color-#acaeb3 font-size-14px w-100px text-right"
              style="line-height: 32px"
              >是否外部资源</div
            >
            <div class="">
              <div class="switch">
                <el-switch v-model="outFile" />
              </div>
            </div>
          </div>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <div class="flex items-center">
        <div class="flex-1 text-left" >
          <el-button type="primary" plain @click="importTemplate" v-if="isShow">
            <Icon icon="ep:download" />
            下载模板
          </el-button>
        </div>
        <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { getToken } from '@/utils/auth'
import download from '@/utils/download'
import requestEx from '@/utils/axios'
import {useMessage} from "@/hooks/web/useMessage";

defineOptions({ name: 'ImportForm' })

const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const uploadRef = ref()
const uploadHeaders = ref() // 上传 Header 头
const fileList = ref([]) // 文件列表
const file = ref('')

const props = defineProps({
  importTemplateData: {
    type: Object,
    required: true
  },
  // 可以导入的文件类型
  accept: {
    type: String,
    required: false,
    default: '.xlsx,.xls'
  },
  // 是否更新已经存在的用户数据.默认值是1
  mode: {
    type: Number,
    required: false,
    default: 1
  },
  // 更新是否禁用,默认值不禁用
  updateIsDisable: {
    type: Boolean,
    required: false,
    default: false
  },
  // 追加是否禁用,默认值不禁用
  appendIsDisable: {
    type: Boolean,
    required: false,
    default: false
  },
  // 覆盖是否禁用,默认值不禁用
  coverIsDisable: {
    type: Boolean,
    required: false,
    default: false
  },
  // 是否部门保存,默认是
  updatePart: {
    type: Boolean,
    required: false,
    default: false
  },
  url: {
    type: String,
    required: false
  },
  // 显示是否外部资源
  isShowOut: {
    type: Boolean,
    required: false,
    default: false
  },
  // 是否显示下载模板按钮
  isShow: {
    type: Boolean,
    required: false,
    default: true
  },
  outFile: {
    type: Boolean,
    required: false,
    default: false
  },
  // 库存修改 扩展额外属性
  fromInventoryStatus: {
    type: String,
    required: false,
    default: ''
  },
  // 库存修改 扩展额外属性
  toInventoryStatus: {
    type: String,
    required: false,
    default: ''
  }
})
const importTemplateData = ref(props.importTemplateData)
const accept = ref(props.accept)
const mode = ref(props.mode) //是否更新已经存在的用户数据.默认值是1
const updateIsDisable = ref(props.updateIsDisable) //更新是否禁用,默认值不禁用
const appendIsDisable = ref(props.appendIsDisable) //追加是否禁用,默认值不禁用
const coverIsDisable = ref(props.coverIsDisable) //覆盖是否禁用,默认值不禁用
const updatePart = ref(props.updatePart) //是否部门保存
const outFile = ref(props.outFile) //是否引入外部资源

const importUrl = import.meta.env.VITE_APP_BASE_API + props.url

/** 打开弹窗 */
const open = () => {
  dialogVisible.value = true
  resetForm()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const submitForm = async () => {
  if (fileList.value.length == 0) {
    message.error('请上传文件')
    return
  }
  file.value = fileList.value[0].name
  // 提交请求
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getToken()
  }
  formLoading.value = true
  uploadRef.value!.submit()
}

/** 文件上传成功 */
const emits = defineEmits(['success'])
const submitFormSuccess = (response: any) => {
  formLoading.value = true
  console.log(response)
  if (response) {
    if (response.code == 500) {
      uploadRef.value!.clearFiles()
      message.error('导入失败')
      formLoading.value = false
      return
    } else if (response.code == 0) {
      if (response.data.errorCount > 0) {
        message.confirm('文件中有部分数据导入失败，是否下载失败数据？').then(() => {
          // download.excel(file, 'file_' + new Date().getTime())
          // 通过url下载文件
          // const downloadElement = document.createElement('a')
          // console.log(172, import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/' + response.data.errorFile)
          // console.log(172, import.meta.env.VITE_BASE_URL + '/admin-api/opt/profile/' + response.data.errorFile)
          window.open(
            import.meta.env.VITE_BASE_URL + '/admin-api' + response.data.errorFile,
            '222'
          )
          // downloadElement.setAttribute('href', import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + response.data.errorFile )
          // 点击下载
          // downloadElement.click()
        })
      } else {
        message.success('导入成功')
      }
    }
  }

  // if (response.code !== 0) {
  //   message.error(response.msg)
  //   formLoading.value = false
  //   return
  // }
  // // 拼接提示语
  // const data = response.data
  // const create = response.data.importResult[0]
  // const update = response.data.importResult[1]
  // const failure = response.data.importResult[2]
  // let text = '上传成功数量：' + data[create].length + ';'
  // for (let name of data[create]) {
  //   text += '< ' + name + ' >'
  // }
  // text += '更新成功数量：' + data[update].length + ';'
  // for (const name of data[update]) {
  //   text += '< ' + name + ' >'
  // }
  // text += '更新失败数量：' + Object.keys(data[failure]).length + ';'
  // for (const name in data[failure]) {
  //   text += '< ' + name + ': ' + data[failure][name] + ' >'
  // }
  // message.alert(text)

  // 发送操作成功的事件

  formLoading.value = false
  emits('success')
  dialogVisible.value = false
}
/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')
  formLoading.value = false
}

/** 重置表单 */
const resetForm = () => {
  // 重置上传状态和文件
  formLoading.value = false
  uploadRef.value?.clearFiles()
  fileList.value = []
}

/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error('最多只能上传一个文件！')
}

/** 下载模板操作 */
const importTemplate = async() => {
  const res= await requestEx.downloadPost({ url:importTemplateData.value.templateUrl });
  download.excel(res, importTemplateData.value.templateTitle)
}

</script>

<style scoped lang="scss">
.tips {
  div {
    position: relative;
    padding-left: 22px;

    &::before {
      width: 4px;
      height: 4px;
      border-radius: 50%;
      content: '';
      background: #c2c2c2;
      position: absolute;
      top: 50%;
      margin-top: -2px;
      left: 4px;
    }
  }
}
</style>
